package news.servlet;

import news.dao.CategoryDao;
import news.dao.NewsDao;
import news.pojo.Category;
import news.pojo.News;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/index") // 首页
public class IndexServlet extends HttpServlet {
    private NewsDao newsDao = new NewsDao();
    private CategoryDao categoryDao = new CategoryDao();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 读取首页的数据
        List<News> topNewsList = new ArrayList<>();
        List<News> hotNewsList = new ArrayList<>();
        List<News> newsList = new ArrayList<>();
        List<Category> cateList = new ArrayList<>();
        try {
            topNewsList = newsDao.selectByLevel(10,5);//置顶新闻
            hotNewsList = newsDao.selectByLevel(5,10);//置顶新闻
            newsList= newsDao.selectByLevel(0,25);//置顶新闻
            cateList = categoryDao.selectAll();
        } catch (SQLException e) {
            e.printStackTrace();
            throw  new ServletException(e.getMessage());
        }
        // 设置显示所书需要的数据
        req.setAttribute("topNewsList",topNewsList);
        req.setAttribute("hotNewsList",hotNewsList);
        req.setAttribute("newsList",newsList);
        req.setAttribute("cateList",cateList); // 分类
        // 转发
        req.getRequestDispatcher("/WEB-INF/views/index.jsp").forward(req, resp);

    }
}
